import React, {ChangeEventHandler, CSSProperties, useState} from "react";
import cs from 'classnames';
import {ColorType} from "./interface";
import {Color} from "./color";
import Palette from "./Palette";
import './index.scss';
import {useControllableValue} from "ahooks";

export interface ColorPickerProps {
  /**
   * 自定义类名
   */
  className?: string;
  /**
   * 自定义样式
   */
  style?: CSSProperties;
  /**
   * 颜色的值
   */
  value?: Color;
  /**
   * 颜色默认的值
   */
  defaultValue?: Color;
  /**
   * 颜色变化的回调
   * @param color
   */
  onChange?: (color: Color) => void;
}

function ColorPickerPanel(props: ColorPickerProps) {

  const {
    className,
    style,
    value,
    defaultValue,
    onChange
  } = props;

  const [colorValue, setColorValue] = useControllableValue<Color>(props);

  const [color, setColor] = useState<Color>(colorValue);


  const classNames = cs("color-picker", className);

  function onPaletteColorChange(color: Color) {
    setColorValue(color);
    setColor(color);
    onChange?.(color);
  }


  const handleHueChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    const hsv = color.toHsv();
    const val = +e.target.value;
    const newColor = new Color({
      h: val,
      s: hsv.s,
      v: hsv.v,
    })
    setColor(newColor)
    setColorValue(newColor)
  }

  const handleVChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    const hsv = color.toHsv();
    const val = +e.target.value;
    const newColor = new Color({
      h: hsv.h,
      s: hsv.s,
      v: val,
    })
    setColor(newColor)
    setColorValue(newColor)
  }

  return <div className={classNames} style={style}>
    <Palette color={colorValue} onChange={onPaletteColorChange}></Palette>
    <div className="color-picker-move">
      <div className="color-picker-move-selector">
        <div>
          色相：<input type='range' min={0} max={360} step={0.1} value={color.toHsv().h} onChange={handleHueChange}/>
        </div>
        <div>
          明度：<input type='range' min={0} max={1} step={0.01} value={color.toHsv().v} onChange={handleVChange}/>
        </div>
      </div>
      <div
        className="color-picker-move-show"
        style={{background: colorValue.toRgbString()}}>
      </div>
    </div>
  </div>
}

export default ColorPickerPanel;
